package com.penjin.android.activity.kaoqin;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.util.NetUtils;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.penjin.android.R;
import com.penjin.android.adapter.KaoqinLateAdapter;
import com.penjin.android.adapter.ListViewAdapter;
import com.penjin.android.constants.HttpConstants;
import com.penjin.android.domain.KaoqinLateData;
import com.penjin.android.domain.KaoqinLateDayData;
import com.penjin.android.domain.KaoqinPersonData;
import com.penjin.android.domain.PenjinDate;
import com.penjin.android.domain.PenjinDepartment;
import com.penjin.android.domain.PenjinUser;
import com.penjin.android.http.HttpService;
import com.penjin.android.service.UserService;
import com.penjin.android.view.CustomProgressDialog;
import com.penjin.android.view.TitleBarView;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by fengjw on 2016/3/20.
 */
public class KaoqinLateActivity extends Activity implements View.OnClickListener{

    private CustomProgressDialog progressDialog;
    DatePickerDialog datePicker;
    com.wdullaer.materialdatetimepicker.date.DatePickerDialog.OnDateSetListener onDateSetListener;
    TextView startDate;

    PenjinUser user;
    PenjinDate todayDate; //今天日期

  //  public List<KaoqinLateData> datas=new ArrayList<KaoqinLateData>();
    public List<KaoqinPersonData> datas=new ArrayList<KaoqinPersonData>();
    private TextView centerView;
    private TitleBarView titleBarView;

    private String title;
    private String url;
    private Context context=this;

    private String userId;
    private String companyId;
    private String time;
    private String yearLate;
    private String monthLate;

    private ListView lv;
    private KaoqinLateAdapter lateAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_activity_kaoqin_late);

        Log.v("fengjw","KaoqinLateActivity");
        Intent intent=getIntent();
        title=intent.getStringExtra("title");

        initData();

        initTitleBar();
    }

    public void initData(){

        startDate = (TextView)findViewById(R.id.kapqin_son_date_image);
        startDate.setOnClickListener(this);
        progressDialog = CustomProgressDialog.createDialog(this);

        this.onDateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
                    startDate.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth );
                    time = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                    yearLate = year+"";
                    monthLate =( monthOfYear+1)+"";
                    Log.d("fengjw", "time1 :" + time);
                    Log.d("fengjw"," year + monthOfYear :" + yearLate + " " + monthLate);
            }
        };

        Date date = new Date();
        int year = date.getYear() + 1900;
        int month = date.getMonth();
        int day = date.getDate();
        datePicker = DatePickerDialog.newInstance(this.onDateSetListener, year, month, day);
        Log.d("fengjw","Date : "+ datePicker);

        user = UserService.getInstance(this.getApplicationContext()).getCurrentUser();
        if (user == null) {
            Toast.makeText(this, "用户尚未登陆！", Toast.LENGTH_SHORT).show();
            finish();
        }
        //Toast.makeText(this, user.getPhone(), Toast.LENGTH_SHORT).show();
        userId=user.getPhone();
        companyId=user.getCompanyId();
        Log.d("fengjw",userId+"   "+companyId);

        if(title.equals("今日迟到榜")) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date curDate = new Date(System.currentTimeMillis());
            time = simpleDateFormat.format(curDate);
            startDate.setText(time);
            Log.d("fengjw","今日迟到榜");
            url= HttpConstants.HOST + HttpConstants.KaoqinPersonLateDay;
            httpLateDay();
        }else if(title.equals("每月迟到榜")){
            Log.d("fengjw","每月迟到榜");

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            Date curDate = new Date(System.currentTimeMillis());
            time = simpleDateFormat.format(curDate);
            startDate.setText(time);

            yearLate = simpleDateFormat.format(curDate).substring(0,4);
            monthLate = simpleDateFormat.format(curDate).substring(5,7);
            Log.d("fengjw","Date:   "+year + " " + month);

            url = HttpConstants.HOST + HttpConstants.KaoqinPersonLateMonth;
            httpLateMonth();
        }else {
            Log.d("fengjw","no title");
        }
    }

    public void httpLateDay(){

        if(datas.isEmpty()){

            HttpService httpService= HttpService.getInstance(this);
            if(NetUtils.hasNetwork(this)){
                try{

                    RequestParams requestParams=new RequestParams();
                    requestParams.put("companyId",companyId);
                    requestParams.put("userName",userId);
                    Log.d("fengjw","time2 "+time);

                    requestParams.put("date",time);
                    //requestParams.put("date","2016-04-01");
                    Log.d("fengjw","DATA:"+userId+" "+companyId);

                    //url

                    httpService.postRequest(this, url, requestParams, new TextHttpResponseHandler() {
                        @Override
                        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                            if (s == null) {
                                Toast.makeText(context, "服务器内部错误", Toast.LENGTH_SHORT).show();
                            } else {
                                System.out.println(s);
                                Toast.makeText(context, "资源路径出错", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onSuccess(int i, Header[] headers, String s) {
                            try {
                                JSONObject jo = new JSONObject(s);

                                if (jo.getBoolean("result")) {
                                    List<KaoqinLateDayData> kaoqinLateDayDataList = new ArrayList();

                                    JSONArray ja = jo.getJSONArray("order");
                                    Log.d("fengjw","order:   "+ja.toString()) ;

                                    JSONObject entity;

                                    if (ja != null && ja.length() > 0) {
                                        for( int j = 0 ; j < ja.length() ; j++){
                                            entity = ja.getJSONObject(j) ;
                                            Log.d("fengjw","entity!");
                                            KaoqinLateDayData kaoqinLateDayData = new KaoqinLateDayData();
                                            kaoqinLateDayData.setName(entity.getString("Name"));
                                            Log.d("fengjw","test 1");
                                            kaoqinLateDayData.setDepartment(entity.getString("Department"));
                                            kaoqinLateDayData.setHeadUrl(entity.getString("HeadUrl"));
                                            kaoqinLateDayData.setScore(entity.getInt("Score"));
                                            kaoqinLateDayData.setLateMintues(entity.getInt("LateMintues"));
                                            Log.d("fengjw","test 2");
                                            kaoqinLateDayData.setStaffNumber(entity.getString("StaffNumber"));

                                            kaoqinLateDayDataList.add(kaoqinLateDayData);
                                            Log.d("fengjw","kaoqinLateDayList : " + kaoqinLateDayDataList.get(j).getName()
                                            + " " + kaoqinLateDayDataList.get(j).getDepartment() + "    "
                                            + kaoqinLateDayDataList.get(j).getHeadUrl() + " "
                                            + kaoqinLateDayDataList.get(j).getStaffNumber() + " "
                                            + kaoqinLateDayDataList.get(j).getScore() + "   "
                                            + kaoqinLateDayDataList.get(j).getLateMintues());
                                        }
                                        lv = (ListView) findViewById(R.id.lv);
                                        lateAdapter = new KaoqinLateAdapter(KaoqinLateActivity.this);
                                        Log.d("fengjw","1");
                                        lateAdapter.setData(kaoqinLateDayDataList);
                                        Log.d("fengjw","2");
                                        lateAdapter.notifyDataSetChanged();
                                        lv.setAdapter(lateAdapter);

                                        Log.d("fengjw","3");

                                    }else {
                                        Toast.makeText(context, "暂无数据信息", Toast.LENGTH_SHORT).show();
                                    }
                                }else{
                                    Log.v("fengjw","no!");
                                }

                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }


            } else {
                Toast.makeText(this, "网络不可用...", Toast.LENGTH_SHORT).show();
            }

        }
    }

    public void httpLateMonth(){if(datas.isEmpty()){

        HttpService httpService= HttpService.getInstance(this);
        if(NetUtils.hasNetwork(this)){
            try{

                RequestParams requestParams=new RequestParams();
                requestParams.put("companyId",companyId);
                requestParams.put("userName",userId);

                //requestParams.put("date",time);
                requestParams.put("year",yearLate);
                requestParams.put("month",monthLate);
                Log.d("fengjw","DATA:"+userId+" "+companyId);

                //url

                httpService.postRequest(this, url, requestParams, new TextHttpResponseHandler() {
                    @Override
                    public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                        if (s == null) {
                            Toast.makeText(context, "服务器内部错误", Toast.LENGTH_SHORT).show();
                        } else {
                            System.out.println(s);
                            Toast.makeText(context, "资源路径出错", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onSuccess(int i, Header[] headers, String s) {
                        try {
                            JSONObject jo = new JSONObject(s);

                            if (jo.getBoolean("result")) {
                                List<KaoqinLateDayData> kaoqinLateDayDataList = new ArrayList();

                                JSONArray ja = jo.getJSONArray("order");
                                Log.d("fengjw","order:   "+ja.toString()) ;

                                JSONObject entity;

                                if (ja != null && ja.length() > 0) {
                                    for( int j = 0 ; j < ja.length() ; j++){
                                        entity = ja.getJSONObject(j) ;
                                        Log.d("fengjw","entity!");
                                        KaoqinLateDayData kaoqinLateDayData = new KaoqinLateDayData();
                                        kaoqinLateDayData.setName(entity.getString("Name"));
                                        Log.d("fengjw","test 1");
                                        kaoqinLateDayData.setDepartment(entity.getString("Department"));
                                        kaoqinLateDayData.setHeadUrl(entity.getString("HeadUrl"));
                                        kaoqinLateDayData.setScore(entity.getInt("Score"));
                                        kaoqinLateDayData.setLateMintues(entity.getInt("LateMintues"));
                                        Log.d("fengjw","test 2");
                                        kaoqinLateDayData.setStaffNumber(entity.getString("StaffNumber"));

                                        kaoqinLateDayDataList.add(kaoqinLateDayData);
                                        Log.d("fengjw","kaoqinLateDayList : " + kaoqinLateDayDataList.get(j).getName()
                                                + " " + kaoqinLateDayDataList.get(j).getDepartment() + "    "
                                                + kaoqinLateDayDataList.get(j).getHeadUrl() + " "
                                                + kaoqinLateDayDataList.get(j).getStaffNumber() + " "
                                                + kaoqinLateDayDataList.get(j).getScore() + "   "
                                                + kaoqinLateDayDataList.get(j).getLateMintues());
                                    }
                                    lv = (ListView) findViewById(R.id.lv);
                                    lateAdapter = new KaoqinLateAdapter(KaoqinLateActivity.this);
                                    Log.d("fengjw","1");
                                    lateAdapter.setData(kaoqinLateDayDataList);
                                    Log.d("fengjw","2");
                                    lateAdapter.notifyDataSetChanged();
                                    lv.setAdapter(lateAdapter);

                                    Log.d("fengjw","3");

                                }else {
                                    Toast.makeText(context, "暂无数据信息", Toast.LENGTH_SHORT).show();
                                }
                            }else{
                                Log.v("fengjw","no!");
                            }

                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }


        } else {
            Toast.makeText(this, "网络不可用...", Toast.LENGTH_SHORT).show();
        }

    }
    }

    public void initTitleBar(){
        centerView = (TextView) findViewById(R.id.titlebar_center_text);
        Intent intent=getIntent();
        String title=intent.getStringExtra("title");
        centerView.setText(title);
        //left
        ImageView leftView=(ImageView)findViewById(R.id.titlebar_left_img);
        leftView.setImageResource(R.drawable.ease_back);
        //right
        ImageView rightView=(ImageView)findViewById(R.id.titlebar_right_img);
        rightView.setVisibility(View.GONE);

        TextView rightText=(TextView)findViewById(R.id.titlebar_right_tv);
        rightText.setVisibility(View.VISIBLE);
        rightText.setText(R.string.kaopin_update);

        titleBarView = (TitleBarView) findViewById(R.id.titleBar);
        titleBarView.setTitleBarListener(new TitleBarView.TitleBarListener() {
            @Override
            public void left(View view) {
                finish();
            }

            @Override
            public void center(View view) {

            }

            @Override
            public void right(View view) {

            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.titlebar_left_img:
                finish();
                break;
            case R.id.kapqin_son_date_image:
                datePicker.show(getFragmentManager(), "hello");
                if(title.equals("今日迟到榜"))
                    httpLateDay();
                if (title.equals("每月迟到榜"))
                    httpLateMonth();
                break;
        }
    }
}
